package zhjb.platform.module.schedule.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import zhjb.platform.module.schedule.bean.DateBlock;
import zhjb.platform.module.schedule.bean.MDate;
import zhjb.platform.module.schedule.bean.ScheduleTask;
import zhjb.platform.web.module.system.bean.User;
import zhjb.platform.web.service.BaseService;

public class ScheduleService extends BaseService {
	/**
	 * 根据年和月获取这个月内的所有日期的有序集合
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public List<MDate> getAllDateInAMonth(int year, int month) {
		int end = 30;
		switch (month) {
		case 0:
		case 2:
		case 4:
		case 6:
		case 8:
		case 9:
		case 11:
			end = 31;
			break;
		default:
			if (month != 1) {
				end = 30;
			} else {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				try {
					Calendar tempCalendar = Calendar.getInstance();
					tempCalendar.setTime(sdf.parse(year + "0301"));
					tempCalendar.add(Calendar.DAY_OF_MONTH, -1);
					end = tempCalendar.get(Calendar.DAY_OF_MONTH);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			break;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		List<MDate> result = new ArrayList<MDate>();
		for (int start = 1; start <= end; start++) {
			MDate date = new MDate();
			date.setYear(year);
			date.setMonth(month + 1);
			date.setDate(start);
			calendar.add(Calendar.DAY_OF_MONTH, start == 1 ? 0 : 1);
			date.setDay(calendar.get(Calendar.DAY_OF_WEEK) - 1);
			result.add(date);
		}
		return result;
	}

	/**
	 * 找到各个日期中的任务
	 * 
	 * @param dateList
	 * @throws ParseException
	 */
	public void findTaskByDay(List<MDate> dateList, User user) throws ParseException {
		MDate min = null;
		MDate max = null;
		for (MDate date : dateList) {
			if (min == null) {
				min = date;
			}
			if (max == null) {
				max = date;
			}
			min = min(min, date);
			max = max(max, date);
		}

		String minString = min.getYear() + "-" + (min.getMonth() > 9 ? min.getMonth() : ("0" + min.getMonth())) + "-" + (min.getDate() > 9 ? min.getDate() : ("0" + min.getDate()));
		String maxString = max.getYear() + "-" + (max.getMonth() > 9 ? max.getMonth() : ("0" + max.getMonth())) + "-" + (max.getDate() > 9 ? max.getDate() : ("0" + max.getDate()));
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date minDate = sdf2.parse(minString + " 00:00:00");
		Date maxDate = sdf2.parse(maxString + " 23:59:59");
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ScheduleTask.class);

		Criterion criterion1 = Restrictions.and(Restrictions.le("start", minDate), Restrictions.ge("end", minDate));
		Criterion criterion2 = Restrictions.and(Restrictions.ge("start", minDate), Restrictions.le("end", maxDate));
		Criterion criterion3 = Restrictions.and(Restrictions.le("start", maxDate), Restrictions.ge("end", maxDate));

		Criterion criterion4 = Restrictions.or(criterion3, Restrictions.or(criterion1, criterion2));
		if (user != null) {
			criterion4 = Restrictions.and(criterion4, Restrictions.eq("user", user.getId()));
		}
		List<ScheduleTask> tasks = dao.findAllByCriteria(detachedCriteria.add(criterion4));
		if (tasks != null && !tasks.isEmpty()) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			Calendar calendar = Calendar.getInstance();
			for (MDate date : dateList) {
				calendar.set(Calendar.YEAR, date.getYear());
				calendar.set(Calendar.MONTH, date.getMonth() - 1);
				calendar.set(Calendar.DAY_OF_MONTH, date.getDate());
				long time = Long.parseLong(sdf.format(calendar.getTime()));
				for (ScheduleTask task : tasks) {
					long start = Long.parseLong(sdf.format(task.getStart()));
					long end = Long.parseLong(sdf.format(task.getEnd()));
					if (start <= time && end >= time) {
						date.getTasks().add(task);
					}
				}
			}

		}
	}

	private MDate min(MDate m1, MDate m2) {
		if (m1.getYear() != m2.getYear()) {
			if (m1.getYear() < m2.getYear()) {
				return m1;
			} else {
				return m2;
			}
		} else {
			if (m1.getMonth() != m2.getMonth()) {
				if (m1.getMonth() < m2.getMonth()) {
					return m1;
				} else {
					return m2;
				}
			} else {
				if (m1.getDate() < m2.getDate()) {
					return m1;
				} else {
					return m2;
				}
			}
		}
	}

	private MDate max(MDate m1, MDate m2) {
		if (m1.getYear() != m2.getYear()) {
			if (m1.getYear() < m2.getYear()) {
				return m2;
			} else {
				return m1;
			}
		} else {
			if (m1.getMonth() != m2.getMonth()) {
				if (m1.getMonth() < m2.getMonth()) {
					return m2;
				} else {
					return m1;
				}
			} else {
				if (m1.getDate() < m2.getDate()) {
					return m2;
				} else {
					return m1;
				}
			}
		}
	}

	/**
	 * 获取月的日期块
	 * 
	 * @return
	 */
	public List<DateBlock> getDateBlock(List<MDate> mDateList) {
		List<MDate> copyDate = new ArrayList<MDate>(mDateList);
		int startDay = copyDate.get(0).getDay();
		List<DateBlock> blockDate = new ArrayList<DateBlock>(35);
		boolean start = false;
		for (int i = 0; i < 42; i++) {
			DateBlock block = new DateBlock();
			block.setIndex(i);
			if (i == startDay) {
				start = true;
			}
			if (start && !copyDate.isEmpty()) {
				block.setDate(copyDate.remove(0));
			}
			blockDate.add(block);
		}
		return blockDate;
	}

	/**
	 * 保存任务
	 * 
	 * @param task
	 */
	public void addTask(ScheduleTask task) {
		dao.saveIObject(task);
	}

	/**
	 * 根据ID获取任务
	 * 
	 * @param ids
	 * @return
	 */
	public List<ScheduleTask> findTasks(Set<String> ids) {
		if (ids != null && !ids.isEmpty()) {
			return dao.findAllByCriteria(DetachedCriteria.forClass(ScheduleTask.class).add(Restrictions.in("id", ids)));
		}
		return new ArrayList<ScheduleTask>();
	}

	public List<ScheduleTask> deleteTaskId(Set<String> ids, String deleteIds) {
		if (deleteIds != null) {
			String sql = "delete from ScheduleTask where id='" + deleteIds + "'";
			dao.execByHQL(sql);
		}
		if (ids != null && !ids.isEmpty()) {
			return dao.findAllByCriteria(DetachedCriteria.forClass(ScheduleTask.class).add(Restrictions.in("id", ids)));
		}
		return new ArrayList<ScheduleTask>();
	}

	public static void main(String[] args) {
		ScheduleService service = new ScheduleService();
		List<MDate> result = service.getAllDateInAMonth(2012, 10);
		for (MDate date : result) {
			System.out.println(date);
		}
		List<DateBlock> list = service.getDateBlock(result);
		for (int i = 0; i < list.size(); i++) {
			System.out.print(list.get(i).getDate() + "\t");
			if ((i + 1) % 7 == 0) {
				System.out.println();
			}
		}
	}
}
